<template>
  <div @click="click" style="width: 130px; hight: 100px">
    <ElUpload
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><plus /></el-icon>
      <div style="font-size: 16px" class="sc">上传照片</div>
    </ElUpload>
  </div>
</template>

<script>
import { ref } from "vue";
import { ElMessage, ElUpload } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import {
  UploadFile,
  ElUploadProgressEvent,
  ElFile,
} from "element-plus/es/components/upload/src/upload.type";
export default {
  components: {
    Plus,
    ElUpload,
  },
  data() {
    return {
      imageUrl: ref(""),
    };
  },
  methods: {
    handleAvatarSuccess(res = ElUploadProgressEvent, file = UploadFile) {
      console.log(res);
      this.imageUrl.value = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file = ElFile) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        ElMessage.error("Avatar picture must be JPG format!");
      }
      if (!isLt2M) {
        ElMessage.error("Avatar picture size can not exceed 2MB!");
      }
      return isJPG && isLt2M;
    },
    click() {
      console.log(1);
    },
  },
};
</script>

<style lang="less" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader {
  width: 100px;
  height: 140px;
  border: 3px dotted #dddada;
  text-align: center;
  line-height: 160px;
  position: relative;
  .icon {
    height: 40px;
    width: 40px;
    color: #dddada;
  }
  .sc {
    position: absolute;
    top: 100px;
    left: 25px;
  }
}
</style>